package com.cn.chaomeng.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.chaomeng.model.Food;
import com.cn.chaomeng.model.Foodtype;
import com.cn.chaomeng.service.IAdminService;
import com.cn.chaomeng.service.IFoodsService;
import com.cn.chaomeng.service.IOrdersService;
import com.cn.chaomeng.utils.DateUtil;
import com.cn.chaomeng.utils.MultipartFileUtil;
import com.cn.chaomeng.vo.AjaxError;
import com.cn.chaomeng.vo.BootstrapTableVo;
import com.cn.chaomeng.vo.BootstrapValidateVo;
import com.cn.chaomeng.vo.form.AdminUserForm;
import com.cn.chaomeng.vo.form.FoodTypeForm;
import com.cn.chaomeng.vo.form.FoodsForm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author LYJ
 *         Created by Administrator on 2018/2/27 0027.
 */
@Controller
@RequestMapping("/admin")
public class AdminController
{

    public final static String SESSION_ADMIN_USER = "adminUser";

    @Resource
    private IFoodsService foodsService;

    @Resource
    private IAdminService adminService;

    @Resource
    private IOrdersService ordersService;

    @RequestMapping("")
    public ModelAndView home()
        throws Exception
    {
        return index();
    }

    @RequestMapping("/index")
    public ModelAndView index()
        throws Exception
    {
        return new ModelAndView("adminLogin");
    }

    @RequestMapping("/login")
    @ResponseBody
    public AjaxError login(HttpServletRequest request, @RequestParam String username, @RequestParam String password)
    {
        AjaxError error;
        AdminUserForm adminUserForm = new AdminUserForm(adminService);
        adminUserForm.setUsername(username);
        adminUserForm.setPwd(password);
        error = adminUserForm.login();
        if (error.isTrue())
        {
            request.getSession()
                .setAttribute(AdminController.SESSION_ADMIN_USER, adminService.selectByUsername(username));
        }
        return error;
    }

    @RequestMapping("/login/validatorUsername")
    @ResponseBody
    public BootstrapValidateVo validateUsername(@RequestParam String username)
        throws Exception
    {
        AdminUserForm adminUserForm = new AdminUserForm(adminService);
        adminUserForm.setUsername(username);
        return new BootstrapValidateVo(!adminUserForm.emptyUsername());
    }

    @RequestMapping("/login/validatorPassword")
    @ResponseBody
    public BootstrapValidateVo validatePassword(@RequestParam String username, @RequestParam String password)
        throws Exception
    {
        AdminUserForm adminUserForm = new AdminUserForm(adminService);
        adminUserForm.setUsername(username);
        adminUserForm.setPwd(password);
        return new BootstrapValidateVo(adminUserForm.validatePwd().isTrue());
    }

    @RequestMapping("/foods")
    public ModelAndView foodsIndex()
        throws Exception
    {
        ModelAndView view = new ModelAndView("admin/food/index");
        view.addObject("foodtype", JSONObject.toJSONString(foodsService.selectFoodType()));
        return view;
    }

    @RequestMapping("/foods/get")
    @ResponseBody
    public BootstrapTableVo getFoods(@RequestParam(required = false) String where,
        @RequestParam(required = false) Integer foodTypeId, @RequestParam Integer offset, @RequestParam Integer limit)
        throws Exception
    {
        return foodsService.getFoodsTable(where, foodTypeId, offset, limit);
    }

    @RequestMapping("/foods/getType")
    @ResponseBody
    public Object getType()
        throws Exception
    {
        return JSONObject.toJSONString(foodsService.selectFoodType());
    }

    @RequestMapping("/foods/add")
    @ResponseBody
    public AjaxError addFoods(@RequestParam(required = false) MultipartFile picurl, @RequestParam Integer typeid,
        @RequestParam String foodName,
        @RequestParam Double foodPrice, @RequestParam Double foodVip, @RequestParam String feature)
        throws Exception
    {
        FoodsForm foodsForm = new FoodsForm(foodsService);
        foodsForm.setTypeid(typeid);
        foodsForm.setFoodname(foodName);
        if (picurl != null)
        {
            foodsForm.setPicurl(MultipartFileUtil.setImage(MultipartFileUtil.FOOD_IMAGE_PATH, picurl));
        }
        foodsForm.setFoodprice(foodPrice);
        foodsForm.setFoodvip(foodVip);
        foodsForm.setFeature(feature);
        AjaxError error = foodsForm.add();
        if (error.getRecode() == 0)
        {
            Food food = FoodsForm.toFood(foodsForm);
            food.setCreateTime(DateUtil.getDateTimeFormat(new Date()));
            food.setState(1);
            if (foodsService.insert(food))
            {
                error.setRecode(0);
            }
            else
            {
                error.setRecode(1);
                error.setError("商品添加错误");
            }
        }
        return error;
    }

    @RequestMapping("/foods/update")
    @ResponseBody
    public AjaxError updateFoods(@RequestParam Integer fid, @RequestParam(required = false) MultipartFile picurl,
        @RequestParam Integer typeid, @RequestParam String foodName,
        @RequestParam Double foodPrice, @RequestParam Double foodVip)
        throws Exception
    {
        AjaxError error = new AjaxError();
        Food food = foodsService.selectById(fid);
        if (food != null)
        {
            FoodsForm foodsForm = new FoodsForm(foodsService);
            foodsForm.setFid(fid);
            foodsForm.setTypeid(typeid);
            foodsForm.setFoodname(foodName);
            if (picurl != null)
            {
                foodsForm.setPicurl(MultipartFileUtil.setImage(MultipartFileUtil.FOOD_IMAGE_PATH, picurl));
            }
            foodsForm.setFoodprice(foodPrice);
            foodsForm.setFoodvip(foodVip);
            error = foodsForm.update();
            if (error.getRecode() == 0)
            {
                if (foodsService.updateById(FoodsForm.toFood(foodsForm)))
                {
                    if (picurl != null)
                    {
                        MultipartFileUtil.deleteImage(food.getPicurl());
                    }
                    error.setRecode(0);
                }
                else
                {
                    error.setError(1, "商品修改错误");
                }
            }
        }
        else
        {
            error.setError(3, "商品修改错误");
        }

        return error;
    }

    private final String UP_OF_STOCK = "up";

    @RequestMapping("/foods/stock")
    @ResponseBody
    public AjaxError deleteFoods(@RequestParam("ids[]") List<Integer> ids, @RequestParam String type)
        throws Exception
    {
        AjaxError error = new AjaxError();
        for (Integer id : ids)
        {
            Food food = new Food();
            food.setFid(id);
            food.setState(UP_OF_STOCK.equals(type) ? 1 : 0);
            if (!foodsService.updateById(food))
            {
                error.setRecode(1);
                error.setError("商品修改错误");

            }
        }
        return error;
    }

    @RequestMapping("/foodtype")
    public ModelAndView foodtypeIndex()
        throws Exception
    {
        ModelAndView view = new ModelAndView("admin/foodtype/index");
        view.addObject("foodtype", JSONObject.toJSONString(foodsService.selectFoodType()));
        return view;
    }

    @RequestMapping("/foodtype/get")
    @ResponseBody
    public BootstrapTableVo getFoodType()
        throws Exception
    {
        return foodsService.getFoodTypeTable();
    }

    @RequestMapping("/foodtype/add")
    @ResponseBody
    public AjaxError addFoodType(@RequestParam(required = false) MultipartFile picurl, @RequestParam String typename)
        throws Exception
    {
        AjaxError error = new AjaxError();
        FoodTypeForm foodTypeForm = new FoodTypeForm(foodsService);
        foodTypeForm.setPicurl(MultipartFileUtil.setImage(MultipartFileUtil.FOOD_TYPE_IMAGE_PATH, picurl));
        foodTypeForm.setTypename(typename);
        if (foodTypeForm.add())
        {
            Foodtype foodtype = FoodTypeForm.toFoodtype(foodTypeForm);
            foodtype.setCreateTime(DateUtil.getDateTimeFormat(new Date()));
            if (foodsService.insertFoodType(foodtype))
            {
                error.setRecode(0);
            }
            else
            {
                error.setRecode(2);
                error.setError("商品添加错误");
            }
        }
        else
        {
            error.setRecode(1);
            error.setError("分类名以存在");
        }
        return error;
    }

    @RequestMapping("/foodtype/update")
    @ResponseBody
    public AjaxError updateFoodtype(@RequestParam Integer typeid, @RequestParam(required = false) MultipartFile picurl,
        @RequestParam String typename)
        throws Exception
    {
        AjaxError error = new AjaxError();
        Foodtype foodtype = foodsService.selectFoodTypeById(typeid);
        if (foodtype != null)
        {
            FoodTypeForm foodTypeForm = new FoodTypeForm(foodsService);
            foodTypeForm.setPicurl(MultipartFileUtil.setImage(MultipartFileUtil.FOOD_TYPE_IMAGE_PATH, picurl));
            foodTypeForm.setTypeid(typeid);
            foodTypeForm.setTypename(typename);
            if (foodTypeForm.update())
            {
                if (foodsService.updateFoodTypeById(FoodTypeForm.toFoodtype(foodTypeForm)))
                {
                    if (picurl != null)
                    {
                        MultipartFileUtil.deleteImage(foodtype.getPicurl());
                    }

                    error.setRecode(0);
                }
                else
                {
                    error.setError(2, "商品修改错误");
                }
            }
            else
            {
                error.setError(1, "分类名以存在");
            }
        }
        else
        {
            error.setError(3, "分类不存在");
        }

        return error;
    }

    @RequestMapping("/foodtype/remove")
    @ResponseBody
    public AjaxError deleteFoodtype(@RequestParam Integer typeid)
        throws Exception
    {
        AjaxError error = new AjaxError();
        Foodtype foodtype = foodsService.selectFoodTypeById(typeid);
        if (foodsService.selectCountByTypeid(typeid) == 0)
        {
            if (foodsService.deleteFoodTypeById(typeid))
            {
                MultipartFileUtil.deleteImage(foodtype.getPicurl());
            }
            else
            {
                error.setRecode(1);
                error.setError("分类删除错误");
            }
        }
        else
        {
            error.setRecode(3);
            error.setError("该分类存在商品");
        }
        return error;
    }

    @RequestMapping("/foodtype/transfer")
    @ResponseBody
    public AjaxError transferFoodType(@RequestParam Integer typeId, @RequestParam Integer targetTypeId)
        throws Exception
    {
        AjaxError error = new AjaxError();
        if (!foodsService.updateTypeIdByTypeId(typeId, targetTypeId))
        {
            error.setError(1, "转移错误");
        }
        return error;
    }

    @RequestMapping("/foodtype/validateFoodTypeName")
    @ResponseBody
    public Object foodTypeValidateFoodTypeName(@RequestParam(required = false) Integer typeid,
        @RequestParam String typename)
        throws Exception
    {
        FoodTypeForm foodTypeForm = new FoodTypeForm(foodsService);
        foodTypeForm.setTypeid(typeid);
        foodTypeForm.setTypename(typename);
        return JSONObject.toJSONString(new BootstrapValidateVo(foodTypeForm.validateTypename()));
    }

    @RequestMapping("/foodSales")
    public ModelAndView foodSales()
        throws Exception
    {
        return new ModelAndView("admin/foodsales/index");
    }

    @RequestMapping("/foodSales/get")
    @ResponseBody
    public BootstrapTableVo getFoodSales()
        throws Exception
    {
        return foodsService.getFoodSalesTable();
    }

    @RequestMapping("/orders")
    public ModelAndView orders()
        throws Exception
    {
        return new ModelAndView("admin/orders/index");
    }

    @RequestMapping("/orders/get")
    @ResponseBody
    public BootstrapTableVo getOrders(@RequestParam Integer offset, @RequestParam Integer limit)
        throws Exception
    {
        return ordersService.getOrdersTable(offset, limit);
    }

    @RequestMapping("/orders/getOrderfo")
    @ResponseBody
    public Object getOrderfo(@RequestParam Integer orderId)
        throws Exception
    {
        return ordersService.selectOrderfoVoByOrderId(orderId);
    }
}
